package com.example.service1.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @oauth Yeohwah
 * @createDate 2021/10/16
 * @info
 */
@Slf4j
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        log.info("===============BlockExceptionHandler=============="+e.getRule());
        httpServletResponse.setCharacterEncoding("utf-8");
        if(e instanceof FlowException){
            new ObjectMapper().writeValue(httpServletResponse.getWriter(),"限流");
        }else if(e instanceof DegradeException){
            new ObjectMapper().writeValue(httpServletResponse.getWriter(),"降级");
        }else if(e instanceof ParamFlowException){
            new ObjectMapper().writeValue(httpServletResponse.getWriter(),"热点限流");
        }else if(e instanceof SystemBlockException){
            new ObjectMapper().writeValue(httpServletResponse.getWriter(),"保护规则");
        }else if(e instanceof AuthorityException){
            new ObjectMapper().writeValue(httpServletResponse.getWriter(),"授权不通过");
        }

    }
}
